package com.codejoys.monitor.startup;

import com.codejoys.monitor.domain.ChannelConfig;
import com.codejoys.monitor.dto.ChannelConfigMap;
import com.codejoys.monitor.mapper.ChannelConfigMapper;
import com.codejoys.monitor.mapper.ChannelMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Component
@Order(1)       // 配置文件优先读取
public class ConfigInitializer implements ApplicationRunner {
    private static final Logger logger = LoggerFactory.getLogger(ConfigInitializer.class);

    @Autowired
    ChannelConfigMapper channelConfigMapper;

    @Autowired
    ChannelMapper channelMapper;

    ChannelConfigMap configMap = new ChannelConfigMap();

    @Autowired
    ApplicationContext context;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        logger.info("读取配置信息。。。");

        final List<ChannelConfig> configs = channelConfigMapper.selectByExample(null);

        final Map<String, ChannelConfig> map = configs.stream()
                .collect(Collectors.toMap(ChannelConfig::getChannel, c -> c));

        configMap.setConfigs(map);

        logger.debug("配置：{}", configMap.getConfigs());
    }

    @Bean
    public ChannelConfigMap provide() {
        return configMap;
    }
}
